<?php

namespace app\api\controller\user;

use think\Controller;


class Auth extends Controller{

    public function __construct(){

        parent::__construct();

        $this->UserModel = model('User.User');
        $this->RegionModel = model('Region');
        $this->ConfigModel = model('Config');
    }

    // 授权登陆
    public function login()
    {
        if($this->request->isPost())
        {
            $code = $this->request->post('code', '');

            if(!$code)
            {
                $this->error('临时授权失败');
                exit;
            }

            //调用微信接口
            $result = $this->code2ession($code);

            $openid = isset($result['openid']) ? $result['openid'] : '';

            if(empty($openid)){
                $this->error('微信授权失败');
                exit;
            }

            //根据openid判断是否有绑定用户,有绑定用户就将用户信息返回,没绑定就去绑定
            $User = $this->UserModel->where(['openid' => $openid])->find();

            if($User){

                $data = [
                    'id'=>$User['id'],
                    'openid'=>$User['openid'],
                    'email'=>$User['email'],
                    'nickname'=>$User['nickname'],
                    'avatar'=>$User['avatar_cdn'],
                    'sex'=>$User['sex'],
                    'sex_text'=>$User['sex_text'],
                    'province'=>$User['province'],
                    'city'=>$User['city'],
                    'district'=>$User['district'],
                    'createtime'=>$User['createtime'],
                    'content'=>$User['content'],
                    'point'=>$User['point'],
                    'vip'=>$User['vip'],
                    'auth'=>$User['auth'],
                    'cover'=>$User['cover_cdn'],
                    'region'=>explode('-', $User['region']),
                    'region_text'=>$User['region']
                ];
                
                $this->success('登录成功', '', $data);
                exit;

            } else {
                $this->success('请先关联账号', '/pages/user/bind', null);
                exit;
            }
        }
    }

    // 微信服务端发送GET请求
    public function code2ession($js_code = null)
    {
        
        if($js_code){

            $appid = 'wx748c34cc67342aba';

            // AppSecret(小程序密钥)	
            $appSecret = 'ad47c6d79126dd9f22e21294887387d7';

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$js_code&grant_type=authorization_code";

            //发起get请求
            $result =$this->https_request($url);

            //获取结果 将json转化为数组
            $resultArr = json_decode($result,true);

            return $resultArr;
        }else{
            return false;
        }

    } 

     //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    // https://www.php.net/manual/zh/book.curl.php
    protected function https_request($url,$data = null)
    {
        if(function_exists('curl_init')){
        $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            // 发送会话，返回结果
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }

    //微信小程序绑定，如果不存在就注册，如果存在就绑定
    public function bind()
    {
        if($this->request->isPost())
        {
            $code = $this->request->post('code', '');
            $email = $this->request->param('email', '');
            $password = $this->request->param('password', '');

            if(!$code)
            {
                $this->error('临时授权失败');
                exit;
            }

            //调用微信接口
            $result = $this->code2ession($code);

            $openid = isset($result['openid']) ? $result['openid'] : '';

            if(empty($openid)){
                $this->error('微信授权失败');
                exit;
            }

            //根据openid判断是否有绑定用户,有绑定用户就将用户信息返回,没绑定就去绑定
            $Useropenid = $this->UserModel->where(['openid' => $openid])->find();

            if($Useropenid){
                $data = [
                    'id'=>$Useropenid['id'],
                    'openid'=>$Useropenid['openid'],
                    'email'=>$Useropenid['email'],
                    'nickname'=>$Useropenid['nickname'],
                    'avatar'=>$Useropenid['avatar_cdn'],
                    'sex'=>$Useropenid['sex'],
                    'sex_text'=>$Useropenid['sex_text'],
                    'province'=>$Useropenid['province'],
                    'city'=>$Useropenid['city'],
                    'district'=>$Useropenid['district'],
                    'createtime'=>$Useropenid['createtime'],
                    'content'=>$Useropenid['content'],
                    'point'=>$Useropenid['point'],
                    'vip'=>$Useropenid['vip'],
                    'auth'=>$Useropenid['auth'],
                    'cover'=>$Useropenid['cover_cdn'],
                    'region'=>explode('-', $Useropenid['region']),
                    'region_text'=>$Useropenid['region']
                ];
    
                $this->success('您已经绑定过，无须重复绑定', null, $data);
                exit;
            }

            $User = $this->UserModel->where(['email' => $email])->find();
            
            // 注册用户并且绑定openid
            if(!$User){

                //生成密码盐
                $salt = randstr(10);
                
                // 密码加密
                $password = md5($password.$salt);

                //获取系统配置表里面的赠送积分  value 查询某个字段的值
                $RegisterPoint = $this->ConfigModel->where(['key' => 'RegisterPoint'])->value('value');

                //判断一下注册积分 是不是一个整数  is_numeric() 函数用于检测变量是否为数字或数字字符串。
                $RegisterPoint = is_numeric($RegisterPoint) ? abs($RegisterPoint) : 0;

                //组装数据
                $data= [
                    'email' => $email,
                    'nickname'=>$email,
                    'password' => $password,
                    'salt' => $salt,
                    'point' => $RegisterPoint,
                    'vip' => 0,
                    'auth' => 0,
                    'openid' => $openid
                ];

                //开始插入数据库  validate 验证器  save()插入数据
                $res = $this->UserModel->validate('common/User/User')->save($data);

                if($res === FALSE)
                {
                    //注册失败
                    // getError 返回操作的结果
                    $this->error($this->UserModel->getError());
                    exit;
                } else{

                    // 注册成功
                    $User = $this->UserModel->where(['openid' => $openid])->find();

                    $data = [
                        'id'=>$User['id'],
                        'openid'=>$User['openid'],
                        'email'=>$User['email'],
                        'nickname'=>$User['nickname'],
                        'avatar'=>$User['avatar_cdn'],
                        'sex'=>$User['sex'],
                        'sex_text'=>$User['sex_text'],
                        'province'=>$User['province'],
                        'city'=>$User['city'],
                        'district'=>$User['district'],
                        'createtime'=>$User['createtime'],
                        'content'=>$User['content'],
                        'point'=>$User['point'],
                        'vip'=>$User['vip'],
                        'auth'=>$User['auth'],
                        'cover'=>$User['cover_cdn'],
                        'region'=>explode('-', $User['region']),
                        'region_text'=>$User['region']
                    ];

                    //注册成功，跳转到登录界面
                    $this->success('注册并绑定成功', null, $data);
                    exit;
                }
            } 
            // 有用户信息绑定openid
            else {

                //人已经找到了，先判断是否被绑定过，是判断密码是否正确，更新语句 openid
                if(!empty($User['openid']))
                {
                    $this->error('您输入的邮箱用户已被绑定，无法再次绑定');
                    exit;
                }

                $password = md5($password.$User['salt']);

                if($password != $User['password']){

                    $this->error('您绑定的账号密码输入错误');
                    exit;
                }

                $data = [
                    'id' => $User['id'],
                    'openid' => $openid
                ];

                // 绑定用户的openid
                $result = $this->UserModel->isUpdate()->save($data);

                if($result === FALSE)
                {
                    $this->error($this->UserModel->getError());
                    exit;
                }

                //重新查询最新的数据返回
                $check = $this->UserModel->where(['email' => $email])->find();

                $data = [
                    'id'=>$check['id'],
                    'openid'=>$check['openid'],
                    'email'=>$check['email'],
                    'nickname'=>$check['nickname'],
                    'avatar'=>$check['avatar_cdn'],
                    'sex'=>$check['sex'],
                    'sex_text'=>$check['sex_text'],
                    'province'=>$check['province'],
                    'city'=>$check['city'],
                    'district'=>$check['district'],
                    'createtime'=>$check['createtime'],
                    'content'=>$check['content'],
                    'point'=>$check['point'],
                    'vip'=>$check['vip'],
                    'auth'=>$check['auth'],
                    'cover'=>$check['cover_cdn'],
                    'region'=>explode('-',$check['region']),
                    'region_text'=>$check['region'],
                ];
    
                $this->success('绑定成功', null, $data);
                exit;
            }
        }
    }

    // 修改资料
    public function profile()
    {
        if($this->request->isPost())
        {
            $param = $this->request->param();

            //获取用户id
            $userid = $this->request->param('id', 0);

            $User = $this->UserModel->find($userid);

            if(!$User)
            {
                $this->error('用户不存在');
                exit;
            }

            // 组装数据
            $data = [
                'id' => $userid,
                'nickname' => $param['nickname'],
                'sex' => $param['sex'],
                'content' => $param['content']
            ];

            //获取城市信息
            $region = $this->request->param('region', 0);

            if(!empty($region))
            {
                //查询地区数据
               $parentpath  = $this->RegionModel->where(['code' => $region])->value('parentpath');

               if(empty($parentpath))
               {
                   $this->error('您所选择的地区不存在,请重新选择');
                   exit;
               }

                //将字符串转换为数组
                $path = explode(',', $parentpath);

                if(count($path) <= 0)
                {
                    $this->error('您所选择的地区不存在,请重新选择');
                    exit;
                }

                if(isset($path[0]))
                {
                    $data['province'] = $path[0];
                }

                if(isset($path[1]))
                {
                    $data['city'] = $path[1];
                }

                if(isset($path[2]))
                {
                    $data['district'] = $path[2];
                }

            }

            //封面
            if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
            {
                $result = upload('cover');

                if($result === FALSE)
                {
                    $this->error('上传封面图片失败');
                    exit;
                }

                //追加头像
                $data['cover'] = 'uploads/'.$result;
            }

            //更新数据库
            $result = $this->UserModel->isUpdate()->save($data);

            if($result === FALSE)
            {
                //说明更新失败了，但是你上传的图片是不能要的，直接删除
                @is_file($data['cover']) && @unlink($data['cover']);

                $this->error('修改个人资料失败');
                exit;
            }else
            {
                //先判断是否有选择新的图片
                if(@is_file($data['cover']))
                {
                    //修改成功后，将原来的图片删除
                    $cover = ltrim($User['cover'],"/");
                    @is_file($cover) && @unlink($cover);
                }

                //直接查询最新的结果在返回
                $UserData = $this->UserModel->find($userid);

                $data = [
                    'id'=>$UserData['id'],
                    'openid'=>$UserData['openid'],
                    'email'=>$UserData['email'],
                    'nickname'=>$UserData['nickname'],
                    'avatar'=>$UserData['avatar_cdn'],
                    'sex'=>$UserData['sex'],
                    'sex_text'=>$UserData['sex_text'],
                    'province'=>$UserData['province'],
                    'city'=>$UserData['city'],
                    'district'=>$UserData['district'],
                    'createtime'=>$UserData['createtime'],
                    'content'=>$UserData['content'],
                    'point'=>$UserData['point'],
                    'vip'=>$UserData['vip'],
                    'auth'=>$UserData['auth'],
                    'cover'=>$UserData['cover_cdn'],
                    'region'=>explode('-', $UserData['region']),
                    'region_text'=>$UserData['region']
                ];

                $this->success('修改资料成功', null, $data);
                exit;
            }
        }
    }

}
